package cn.jhc.sevlet;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.Course;
import cn.jhc.dao.CourseDao;
import cn.jhc.dao.impl.CourseDaoImpl;

/**
 * Servlet implementation class AddCourseServlet
 */
@WebServlet("/user/teacher/addcourse.do")
public class AddCourseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCourseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		boolean flag;
		try{
			String coursename = request.getParameter("coursename");
			int classhour = Integer.valueOf(request.getParameter("classhour"));
			BigDecimal credit = new BigDecimal(request.getParameter("credit"));
			int term = Integer.valueOf(request.getParameter("term"));
			Course course = new Course();
			CourseDao courseDao = new CourseDaoImpl();
			course.setCoursename(coursename);
			course.setTerm(term);
			course.setCredit(credit);
			course.setClasshour(classhour);
			courseDao.save(course);
			flag = true;
		} catch(Exception e){
			flag = false;
		}
		
		if(flag){
			response.sendRedirect("../index.jsp");
		}else{
			request.setAttribute("flag", false);
			request.getRequestDispatcher("addcourse.jsp").forward(request,
					response);
		}
		
	}

}
